package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.apis.article.IArticleClient;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.yc.service.ContentScanService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.*;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private Tess4jClient tess4jClient;
    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private ContentScanService contentScanService;
    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        // 1.根据id查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            log.error("文章不存在");
            throw new RuntimeException("文章不存在");
        }
        //如果文章的状态是提交待审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //获取文章的内容和图片
            Map<String, Object> textAndImages = handleTextAndImages(wmNews);
            List<String> list = (List<String>) textAndImages.get("images");
            //识别图片中的内容保存在imgContents中
            StringBuffer imgContents=new StringBuffer();
//            if (tess4jClient!=null){
//                for (String imageUrl : list){
//                    try {
//                        BufferedImage image = ImageIO.read(new URL(imageUrl));
//                        String imgContent = tess4jClient.doOCR(imageUrl);
//                        if (imgContent!=null){
//                            imgContents.append(imgContent +"-");
//                        }
//                    } catch (IOException e) {
//                        log.error("Io错误");
//                    } catch (TesseractException e) {
//                        log.error("tess4j的错误");
//                    }
//                }
//            }



            //2.审核文本内容  阿里云接口
            String content = (String) textAndImages.get("content")+"-"+imgContents;
            boolean isTextScan = handleTextScan(content, wmNews);
            if (!isTextScan) {
                return;
            }

            //3.审核图片  阿里云接口
            boolean isImageScan = handleImageScan(list, wmNews);
            if (!isImageScan) {
                return;
            }

        }
        // 3.返回审核结果
        //4.审核成功，保存app端的相关的文章数据
        ResponseResult responseResult = saveAppArticle(wmNews);
        if(!responseResult.getCode().equals(200)){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
        }
        //回填article_id
        wmNews.setArticleId((Long) responseResult.getData());
        updateWmNews(wmNews,(short) 9,"审核成功");
    }

    /**
     * 保存app端相关的文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        return articleClient.saveArticle(dto);

    }
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        //TODO 审核图片太贵了不做审核直接通过吧,后面有钱再加上
        return true;
    }


    private boolean handleTextScan(String content, WmNews wmNews) {
        //是否通过审核
        boolean flag = true;

        try {
            Map<String, Object> map = contentScanService.greenTextScan(wmNews.getTitle()+content);
            //响应成功
            boolean success = (boolean) map.get("success");
            if (success) {
                String riskLevel = (String) map.get("riskLevel");
                if ("high".equals(riskLevel)) {
                    flag=false;
                    updateWmNews(wmNews, (short) 2,
                            "存在违规内容: "+map.get("riskTips")+"违规关键字: "+map.get("riskWords"));
                } else if ("medium".equals(riskLevel)) {
                    flag=false;
                    updateWmNews(wmNews, (short) 3,
                            "存在不确定内容:"+map.get("riskTips")+"违规关键字: "+map.get("riskWords"));
                } else if ("low".equals(riskLevel)||riskLevel==null){
                    //低风险改为审核通过
                    flag=true;
                }else {
                    flag = true;
                    log.error("审核文本内容失败");
                    throw new RuntimeException("审核文本内容失败");
                }
            }
        }catch (Exception e){
            flag = false;
            log.error("审核文本内容失败");
            throw new RuntimeException("审核文本内容失败");
        }
        return flag;
    }

    /**
     * 修改文章内容
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        //把违规的理由传过去
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        HashMap<String, Object> resultMap = new HashMap<>();

        StringBuilder stringBuilder = new StringBuilder();
        if (wmNews.getContent() != null) {
            List<String> images = new ArrayList<>();
            //json解析为map
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if ("text".equals(map.get("type"))) {
                    stringBuilder.append(map.get("value"));
                }

                if ("image".equals(map.get("type"))) {
                    images.add((String) map.get("value"));
                }
            }
            resultMap.put("content", stringBuilder.toString());
            resultMap.put("images", images);
            return resultMap;
        } else {
            return null;

        }

    }


}